//
//  TTImageChooseView.m
//  TaoTuo
//
//  Created by admin on 2019/12/10.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTImageChooseView.h"
#import <UIImageView+WebCache.h>

@interface TTImageChooseView ()

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIButton *chooseBtn;

@property (nonatomic, copy) chooseBlock clickChooseBtnBlock;

@property (nonatomic, assign) int flags;

@end

@implementation TTImageChooseView


- (instancetype)initWithFrame:(CGRect)frame chooseBlock:(nonnull chooseBlock)chooseBlock flags:(int)flags
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.clickChooseBtnBlock = chooseBlock;
        self.flags = flags;
        self.subject = [RACSubject subject];
        
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.layer.cornerRadius = 5;
        _imageView.layer.masksToBounds = YES;
        _imageView.userInteractionEnabled = YES;
        [self addSubview:_imageView];
        [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.mas_equalTo(10);
            make.right.bottom.mas_equalTo(-10);
        }];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [_imageView addGestureRecognizer:tap];
        
        _chooseBtn = [UIButton createButtonWithNormalImage:[UIImage imageNamed:@"address_unsel"] selectedImage:[UIImage imageNamed:@"address_sel"] target:self action:@selector(chooseBtnClick:)];
        _chooseBtn.selected = YES;
        [self addSubview:_chooseBtn];
        [_chooseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.equalTo(self);
            make.width.height.mas_equalTo(30);
        }];
        
    }
    return self;
}

- (void)tapAction
{
    [self.subject sendNext:@(self.flags)];
}

- (void)chooseBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    if (self.clickChooseBtnBlock) {
        self.clickChooseBtnBlock(self.imageView.image, sender.selected);
    }
    
}


- (void)setImageUrlString:(NSString *)imageUrlString
{
    _imageUrlString = imageUrlString;
    
    @weakify(self)
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:imageUrlString] placeholderImage:[UIImage imageNamed:@"f_placeholder_img"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        @strongify(self)
        
        if (self.clickChooseBtnBlock) {
            self.clickChooseBtnBlock(self.imageView.image, self.chooseBtn.selected);
        }
        
    }];
}

@end



